<template>
  <InlineLayout title-name="缴费明细列表">
    <template #header>
      <my-form ref="queryFormRef" v-model:modelValue="queryParams" :model="queryParams" :items-datas="itemsDatas">
        <my-button type="reset" title="重置" @click="reset" />
        <my-button type="search" title="查询" :loading="loading" @click="handleQuery" />
      </my-form>
    </template>

    <template #titleTools>
      <my-button type="delete" title="删除" @click="handleDel" />
      <el-upload
        class="upload-demo"
        :action="batchUploadUrl"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        name="file"
        :show-file-list="false"
        :data="paramsDataObj"
        :on-success="handleSuccess"
        :on-error="handleError"
        :headers="headers"
        :limit="1"
        style="display: inline-block; margin: 0 10px; vertical-align: top"
      >
        <my-button type="import" title="导入缴费明细" />
      </el-upload>
      <my-button type="export" title="下载导入模板" @click="handleDown" />
      <my-button v-hasPermi="['yuanshidian:ab04:addd']" type="add" title="新增缴费" @click="handleAdd" />
      <my-button v-hasPermi="['yuanshidian:ab04:exportab04jf']" type="export" title="人员缴费导出" @click="handleRefund" />
      <my-button v-hasPermi="['yuanshidian:ab04:export']" type="export" title="缴费导出" @click="handleExport" />
    </template>

    <my-table :columns="columns" :table-data="tableData" @selection-change="handleSelectionChange">
      <template #status="scope">
        <span v-if="scope.row.status === 1">待提交</span>
        <span v-if="scope.row.status === 2" style="color: #e6a23c">审核中</span>
        <span v-if="scope.row.status === 3" style="color: #67c23a">已审核</span>
        <span v-if="scope.row.status === 4" style="color: #f56c6c">驳回</span>
      </template>
      <template #operation="scope">
        <el-upload
          v-if="scope.row.status === 1 || scope.row.status === 4"
          v-hasPermi="['yuanshidian:ab04:ab04upload']"
          class="upload-demo"
          :action="uploadImgUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          name="file"
          :show-file-list="false"
          :data="paramsDataObj"
          :on-success="handleSuccess"
          :on-error="handleError"
          :headers="headers"
          :limit="1"
          style="display: inline-block"
          :file-list="fileList"
        >
          <el-button link type="primary" @click="updateFile(scope.row)">上传附件</el-button>
        </el-upload>
        <el-button link type="primary" @click="lookFile(scope.row)">查看附件</el-button>
        <my-button v-if="scope.row.status === 3" link type="text" expand-type="danger" @click="handleReturn(scope.row)">驳回</my-button>
        <my-button type="text" @click="handleDetail(scope.row)">详情</my-button>
        <el-button
          v-if="scope.row.status === 1 || scope.row.status === 4"
          v-hasPermi="['yuanshidian:ab04:submit']"
          link
          type="primary"
          @click="handleSumbit(scope.row)"
          >提交</el-button
        >
        <el-button
          v-if="scope.row.status === 1 || scope.row.status === 4"
          v-hasPermi="['yuanshidian:ab04:edit']"
          link
          type="primary"
          @click="handleUpdate(scope.row)"
          >修改</el-button
        >
        <!-- <my-button type="text">比对</my-button> -->
        <my-button v-if="scope.row.status === 2" v-hasPermi="['yuanshidian:ab04:examine']" type="text" @click="handleAudit(scope.row)"
          >审核</my-button
        >
        <!--        <el-button v-if="scope.row.status === 3" link type="primary" @click="handleInterest(scope.row)">利息计息</el-button>-->
      </template>
    </my-table>
    <template #footer>
      <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </template>
  </InlineLayout>
  <addOrEdit v-model="dialog.visible" :dialog-title="dialog.title" :current-row="currentRow" @handle-query="handleQuery" />
  <interest v-model="dialog.isShow" :dialog-title="dialog.title" :current-row="currentRow" @handle-query="handleQuery" />
  <audit v-model="dialog.auditIsShow" :current-row="currentRow" @audit-sumbit="auditSumit" />
</template>

<script setup name="Ab04" lang="ts">
import { listAb04, getAb04, delAb04, addAb04, updateAb04, examine, turndownab04, delAbBatch04 } from '@/api/yuanshidian/ab04';
import { addAb04new } from '@/api/yuanshidian/ab04new';
import { Ab04VO, Ab04Query, Ab04Form } from '@/api/yuanshidian/ab04/types';
import { globalHeaders } from '@/utils/request';
import audit from '@/views/components/audit/index.vue';
import addOrEdit from './components/addOrEdit.vue';
import interest from './components/interest';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const currentRow = ref({});
const dw01Arr = ref([]);
const dw02Arr = ref([]);
const queryFormRef = ref<ElFormInstance>();
const headers = ref(globalHeaders());
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + '/yuanshidian/ab04/ab04upload'); // 上传的图片服务器地址
const batchUploadUrl = ref(baseUrl + '/yuanshidian/ab04/import'); // 下载导入模板地址
const fileList = ref([]);

const paramsDataObj = ref({});
const dialog = reactive<DialogOption>({
  visible: false,
  auditIsShow: false,
  isShow: false,
  title: ''
});

const state = reactive({
  itemsDatas: [
    { label: '单位编码', prop: 'dw01', type: 'input' },
    /*{ label: '单位名称', prop: 'dw02', type: 'input' },*/
    { label: '姓名', prop: 'gr04', type: 'input' },
    { label: '个人账号', prop: 'gr03', type: 'input' },
    /*{ label: '证件号码', prop: 'gr02', type: 'input' },*/
    { label: '缴费时间', prop: 'grmx03', type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
  ],
  tableData: [],
  columns: [
    { label: '序号', type: 'index', width: '55', prop: 'index' },
    { type: 'selection' },
    { label: '统筹区编码', prop: 'aaa027', align: 'center', width: '150' },
    { label: '单位编码', prop: 'dw01', align: 'center', width: '150' },
    /*{ label: '单位名称', prop: 'dw02', align: 'center', width: '150' },*/
    { label: '姓名', prop: 'gr04', align: 'center', width: '100' },
    { label: '个人账号', prop: 'gr03', align: 'center', width: '150' },
    /*{ label: '身份证号码', prop: 'gr02', align: 'center', width: '150' },*/
    { label: '本期个人缴费', prop: 'gr20', align: 'center', width: '150' },
    { label: '单位划转额', prop: 'grmx04', align: 'center', width: '150' },
    { label: '本期单位代缴', prop: 'grmx05', align: 'center', width: '150' },
    { label: '个人缴费基数', prop: 'gr19', align: 'center', width: '150' },
    { label: '计息年度', prop: 'grjx01', align: 'center', width: '150' },
    { label: '缴费月度', prop: 'grmx02', align: 'center', width: '150' },
    { label: '缴费时间', prop: 'grmx03', align: 'center', width: '150' },
    // { label: '个人储蓄金额', prop: 'dw12', align: 'center', width: '150' },
    // { label: '本人补充金额', prop: 'dw12', align: 'center', width: '150' },
    { label: '数据状态', prop: 'status', align: 'center', type: 'custom', slot: 'status', width: '80' },
    { label: '操作', type: 'operation', minWidth: '340px' }
  ],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    delStatus: 0,
    dw01: '',
    dw02: '',
    gr04: '',
    gr02: '',
    grmx03: []
  }
});
const { itemsDatas, tableData, columns, queryParams } = toRefs(state);
/** 查询原人员账户明细(缴费明细)列表 */
const getList = async () => {
  loading.value = true;
  const [jfStarttime, jfEndtime] = queryParams.value.grmx03;
  var params = {
    ...queryParams.value,
    jfStarttime,
    jfEndtime
  };
  delete params.grmx03;
  const res = await listAb04(params);
  tableData.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: Ab04VO[]) => {
  ids.value = selection.map((item) => item.id);
  dw01Arr.value = selection.map((item) => item.dw01);
  dw02Arr.value = selection.map((item) => item.dw02);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
//查看附件
const lookFile = (row) => {
  if (!row.fileurl) {
    proxy?.$modal.msgError('没有可查看的附件');
    return;
  }
  window.open(row.fileurl, '_blank');
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  currentRow.value.type = 'add';
  currentRow.value.id = '';
  dialog.visible = true;
  dialog.title = '添加人员账户明细(缴费明细)';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: Ab04VO) => {
  currentRow.value.id = row.id;
  currentRow.value.type = 'edit';
  dialog.title = '修改原人员账户明细(缴费明细)';
  dialog.visible = true;
};
/** 查看详情 */
const handleDetail = (row) => {
  currentRow.value.id = row.id;
  currentRow.value.type = 'detail';
  dialog.title = '查看原单位信息';
  dialog.visible = true;
};
//提交
const handleSumbit = async (row) => {
  var res = await updateStatus(row.id);
  proxy?.$modal.msgSuccess('提交成功');
  await getList();
};
const handleAudit = (data) => {
  currentRow.value = data;
  dialog.auditIsShow = true;
};
//审核
const auditSumit = async (data) => {
  var params = {
    ...data,
    //id: currentRow.value.id,
    examinedataType: 3
  };
  var res = await examine(params);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('审核成功');
    addAb04new(currentRow.value);
  }
  getList();
};
//上传附件
const updateFile = (data) => {
  paramsDataObj.value.ID = data.id;
};
const handlePreview = () => {};
const handleRemove = () => {};
//附件大小限制
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'application/pdf';
  const isLt2M = file.size / 1024 / 1024 < 10;
  if (!isJPG) {
    proxy?.$modal.msgError('附件格式为jpg、png、pdf，请重新上传!');
  }
  if (!isLt2M) {
    proxy?.$modal.msgError('上传附件大小不能超过 10MB!');
  }
  return isLt2M && isJPG;
};
//附件上传成功回调
const handleSuccess = (data) => {
  if (data.code === 200) {
    proxy?.$modal.msgSuccess(data.msg);
    fileList.value = [];
    getList();
  } else {
    proxy?.$modal.msgError(data.msg);
  }
};
//附件上传失败回调
const handleError = (data) => {
  proxy?.$modal.msgSuccess(data.msg);
};

/** 删除按钮操作 */
const handleDelete = async (row?: Ab04VO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除原人员账户明细(缴费明细)编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delAb04(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'yuanshidian/ab04/export',
    {
      ...queryParams.value,
      splitID: ids.value.length > 0 ? ids.value.join(',') : ''
    },
    `ab04_${new Date().getTime()}.xlsx`
  );
};
/** 导出按钮操作 */
const handleRefund = () => {
  if (ids.value.length === 0) {
    proxy?.$modal.msgError('请选择需要导出的数据');
    return;
  }
  proxy?.download(
    'yuanshidian/ab04/exportab04jf',
    {
      splitID: ids.value.length > 0 ? ids.value.join(',') : tableData.value.map((item) => item.id).join(','),
      dw01: dw01Arr.value.length > 0 ? [...new Set(dw01Arr.value)].join(',') : tableData.value.map((item) => item.dw01).join(','),
      dw02: dw02Arr.value.length > 0 ? [...new Set(dw02Arr.value)].join(',') : tableData.value.map((item) => item.dw02).join(',')
    },
    `试点期间参保人员缴费确认表_${new Date().getTime()}.xlsx`
  );
};
//驳回
const handleReturn = async (data) => {
  var res = await turndownab04(data.id);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('驳回成功');
  }
  getList();
};
//利息计息
const handleInterest = (row) => {
  currentRow.value.id = row.id;
  dialog.title = '利息计息';
  dialog.isShow = true;
};
//批量删除
const handleDel = async (row) => {
  if (ids.value.length === 0) {
    proxy?.$modal.msgError('请选择需要删除的数据');
    return;
  }
  await proxy?.$modal.confirm('是否确认缴费明细信息编号为"' + ids.value + '"的数据项？').finally(() => (loading.value = false));
  await delAbBatch04(ids.value);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const handleDown = () => {
  proxy?.download('yuanshidian/ab04/downloadTemplate', {}, `缴费明细导入模板.xlsx`);
};
onMounted(() => {
  getList();
});
</script>
